package pub.xspace.nova.framework.security.service;

import java.util.List;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import pub.xspace.nova.system.domain.SysRole;
import pub.xspace.nova.system.domain.SysUser;
import pub.xspace.nova.system.service.SysRoleService;
import pub.xspace.nova.system.service.SysUserService;

/**
 * 自定义验证用户获取方法
 * 
 * @author HeJianrong
 */
@Service
public class NovaUserDetailsService implements UserDetailsService {

	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysRoleService sysRoleService;

	/**
	 * 通过数据库获取用户信息
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser sysUser = sysUserService.getByUsername(username);
		if (sysUser == null) {
			throw new UsernameNotFoundException(username);
		}
		List<SysRole> roles = sysRoleService.getByUserId(sysUser.getId());
		String[] roleCodes = roles.stream().map(SysRole::getCode).toArray(String[]::new);
		return User.builder().username(sysUser.getUsername()).password(sysUser.getPassword()).roles(roleCodes).build();
	}

}
